package com.cskaoyan.service.system;

import com.cskaoyan.bean.system.Admin;
import com.cskaoyan.bean.system.AdminExample;
import com.cskaoyan.bo.system.AdminCreateBo;
import com.cskaoyan.bo.system.AdminListBo;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.vo.system.AdminCreateVo;
import com.cskaoyan.vo.system.AdminListItemVo;
import com.cskaoyan.vo.system.AdminListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Override
    public AdminListVo adminList(AdminListBo adminListBo) {
        PageHelper.startPage(adminListBo.getPage(), adminListBo.getLimit());

        AdminExample adminExample = new AdminExample();
        adminExample.setOrderByClause(adminListBo.getSort() + " " + adminListBo.getOrder());

        AdminExample.Criteria criteria = adminExample.createCriteria();
        if (null != adminListBo.getUsername())
            criteria.andUsernameLike("%" + adminListBo.getUsername() + "%");

        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        PageInfo<Admin> adminPageInfo = new PageInfo<>(adminList);
        long total = adminPageInfo.getTotal();

        List<AdminListItemVo> voList = adminMapper.selectAdminList(adminListBo);

        AdminListVo adminListVo = new AdminListVo();
        adminListVo.setItems(voList);
        adminListVo.setTotal(total);

        return adminListVo;
    }

    @Override
    public AdminCreateVo adminCreate(AdminCreateBo adminCreateBo) {
        int affectedRows = adminMapper.insertAdmin(adminCreateBo);
        if (1 == affectedRows)
            return adminMapper.selectAdminById(adminCreateBo.getId());
        return null;
    }

    @Override
    public AdminCreateVo adminUpdate(AdminCreateBo adminCreateBo) {
        int affectedRows = adminMapper.updateAdmin(adminCreateBo);
        if (1 == affectedRows) {
            AdminCreateVo adminCreateVo = adminMapper.selectAdminById(adminCreateBo.getId());
            return adminCreateVo;
        }
        return null;
    }

    @Override
    public int delete(AdminCreateBo adminCreateBo) {
        // int affectedRows = adminMapper.deleteByPrimaryKey(adminCreateBo.getId());

        int affectedRows = adminMapper.deleteByIdLogically(adminCreateBo.getId());
        return affectedRows;
    }


}
